package edu.jd.common;

import com.alibaba.fastjson.JSON;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

public class Utils {
    private static final String MYBATIS_CONFIG = "mybatis.xml";
    private static final SqlSessionFactory FACTORY = buildFactory();

    public static SqlSessionFactory buildFactory(){
        InputStream in = null;
        try {
            in = Resources.getResourceAsStream(MYBATIS_CONFIG);
            return new SqlSessionFactoryBuilder().build(in);
        } catch (IOException e) {
            e.printStackTrace();
            //RuntimeException是非受检异常
            throw new RuntimeException("创建session工厂失败", e);
        }
    }

    public static SqlSessionFactory getFactory(){
        return FACTORY;
    }

    public static SqlSession openFactory(){
        return FACTORY.openSession();
    }

    public static void outJson(HttpServletResponse resp, Object obj) throws IOException {
        resp.setContentType("application/json;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        String jsonString = JSON.toJSONString(obj);
        out.println(jsonString);
        //out.print("这是一个测试");
        out.flush();
        out.close();
    }

    public static void outResult(HttpServletResponse resp, Result obj) throws IOException{
        outJson(resp, obj);
    }
}
